package com.ruoyi.crm.modules.quartz;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Service
@Slf4j
public class RemindedService {
    public static final String JOB_GROUP_REMIND = "job_group_remind";

    @Resource
    private Scheduler scheduler;

    /**
     * 在指定时间的发短信提示
     * @param startTime
     * @param taskKey 例如 task:clue:1001, task:business:2008
     * @param phone
     * @param message
     */
    public void createJob(LocalDateTime startTime, String taskKey, String phone, String message) {
        try {
            JobKey jobKey = getJobKey(taskKey);
            if(scheduler.checkExists(jobKey)) {
                scheduler.deleteJob(jobKey);
                log.debug("删除定时任务成功:{}", jobKey);
            }
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("message", message);
            jobDataMap.put("phone", phone);
            jobDataMap.put("startTime", startTime);
            JobDetail jobDetail = JobBuilder.newJob(RemindedJob.class)
                    .withIdentity(jobKey)
                    .usingJobData(jobDataMap)
                    .build();
            // 创建cron表达式指定任务执行的时间，由于时间是确定的，所以年月日时分秒都是确定的，这也符合任务只执行一次的要求。
            String startCron = String.format("%d %d %d %d %d ? %d",
                    0,
                    startTime.getMinute(),
                    startTime.getHour(),
                    startTime.getDayOfMonth(),
                    startTime.getMonth().getValue(),
                    startTime.getYear());

            CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                    // 指定触发器组名和触发器名
                    .withIdentity(getTriggerKey(taskKey))
                    .withSchedule(CronScheduleBuilder.cronSchedule(startCron))
                    .build();
            // 将job和trigger添加到scheduler里
            scheduler.scheduleJob(jobDetail, cronTrigger);
            if (log.isDebugEnabled()) {
                log.debug("定时任务添加成功：{},{},{}", jobDetail.getKey(), cronTrigger.getKey());
                log.debug("定时任务执行规则：{}", startCron);
            }
        } catch (SchedulerException e) {
            log.error("添加定时提醒任务失败", e);
            throw new RuntimeException("添加定时提醒任务失败" + e.getMessage());
        }
    }

    private JobKey getJobKey(String taskId) {
        return JobKey.jobKey(taskId, JOB_GROUP_REMIND);
    }

    private TriggerKey getTriggerKey(String taskId) {
        return TriggerKey.triggerKey(taskId, JOB_GROUP_REMIND);
    }
}
